package com.blt.govdata.controller;

import com.baomidou.mybatisplus.entity.Column;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.blt.govdata.controller.base.BaseController;
import com.blt.govdata.core.constants.Constants;
import com.blt.govdata.core.token.TokenKey;
import com.blt.govdata.model.TSysRole;
import com.blt.govdata.model.TSysUser;
import com.blt.govdata.model.vo.TSysMenuVo;
import com.blt.govdata.model.vo.TSysUserVo;
import com.blt.govdata.service.*;
import com.blt.govdata.utils.DESPlus;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户管理前端控制器
 * </p>
 * @author AustinGJ123
 * @since 2018-03-24
 */
@RestController
@CrossOrigin
@RequestMapping("/tSysUser")
//todo 将所有的XXX修改为真实值
public class TSysUserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITSysUserService service;

    @Autowired
    private ITSysUserRoleService userRoleService;

    @Autowired
    private ITSysRoleService roleService;

    @Autowired
    private ITSysUserOrgService userOrgService;

    @Autowired
    private ITSysOrganizationService organizationService;

    @Autowired
    private ITSysMenuService menuService;



    /**
     * 分页查询用户
     * size:分页大小
     * current:当前页
     */
    @RequestMapping("/page")
    public Map<String, Object> getUsersPage(@RequestParam Map<String, Object> params, Page<TSysUserVo> page) {
        Page<TSysUserVo> result = service.selectUserPage(page, params);
        logger.info("分页查询用户");
        return ImmutableMap.of("status", "true", "data", result);
    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "/login", params = {"userName", "password"})
    public Map<String, Object> userLogin(String userName, String password) {

        TSysUser user = this.service.selectOne(new EntityWrapper<TSysUser>().where("name = {0}", userName)
                .and("password = {0}", password)
                .and("in_use = {0}", 1));
        if (null == user) return ImmutableMap.of("status", "false", "msg", "用户名或密码错误");
        session.setAttribute(Constants.CURRENT_USER, user);
        session.setAttribute(Constants.CURRENT_USERID, user.getId());
        session.setAttribute(Constants.CURRENT_USERNAME, user.getName());
        log("用户登录", "true");
        user.setPassword(""); //去密码
        return ImmutableMap.of("status", "true", "msg", "登陆成功", "data", user);
    }

    /**
     * 获取用户token
     */
    @RequestMapping("/token")
    public Map<String, Object> token(@RequestParam String userName, @RequestParam String password) {
//        TSysUser sessionUser = (TSysUser) session.getAttribute(Constants.CURRENT_USER);
//        if(sessionUser == null) return ImmutableMap.of("status","false","msg","用户未登录");
        TSysUser user = this.service.selectOne(new EntityWrapper<TSysUser>().where("Name = {0}", userName)
                .and("Password = {0}", password)
                .and("In_Use = {0}", 1));
        if (null == user) return ImmutableMap.of("status", "false", "msg", "用户名或密码错误");
        String token = null;
        try {
            token = new DESPlus().encode(TokenKey.KEY+"," + user.getId()+"," + user.getName() +  "," + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        session.setAttribute(Constants.TOKEN, token);
        logger.info("获取token");
        return ImmutableMap.of("status", "true", "token", token);
    }

    /**
     * 新增用户
     */
    @PostMapping("/addUser")
    public Map<String, Object> addUser(TSysUser sysUser) {
        boolean result = this.service.insert(sysUser);
        logger.info("新增用户");
        return ImmutableMap.of("status", "true", "data", result);
    }

    /**
     * 编辑用户
     */
    @PostMapping("/editUser")
    public Map<String, Object> editUser(TSysUser sysUser) {
        if (sysUser != null) {
            /**
             * 不更新用户名和密码
             * */
            sysUser.setName(null);
            sysUser.setPassword(null);
        }
        boolean result = this.service.updateById(sysUser);
        logger.info("编辑用户");
        return ImmutableMap.of("status", "true", "data", result);
    }


    /**
     * 修改/重置密码
     */
    @PostMapping("/resetPassword")
    public Map<String, Object> resetPassword(TSysUser sysUser) {
        boolean result = this.service.updateById(sysUser);
        logger.info("重置用户密码");
        return ImmutableMap.of("status", "true", "data", result);
    }

    /**
     * 删除用户
     * In_Use
     */
    @PostMapping("/deleteUser")
    public Map<String, Object> deleteUser(TSysUser sysUser) {
        if (null == sysUser || sysUser.getId() == null) ImmutableMap.of("status", "false", "data", false);
        sysUser.setInUse(0);
        boolean result = this.service.updateById(sysUser);
        logger.info("逻辑删除用户");
        return ImmutableMap.of("status", "true", "data", result);
    }

    /**
     * 根据Id查询用户
     */
    @RequestMapping(value = "/selectUserById", params = {"id"})
    public Map<String, Object> selectUserById(Integer id) {
        TSysUser user = this.service.selectById(id);
        if (null == user) ImmutableMap.of("status", "false", "msg", "未查询到用户信息");
        user.setPassword("");
        return ImmutableMap.of("status", "true", "data", user);
    }

    /**
     * 用户登出
     */
    @RequestMapping(value = "/loginOut")
    public void loginOut(HttpSession session) {
        session.invalidate();
    }

    /**
     * 查询用户拥有的角色
     */
    @RequestMapping(value = "/selectUserRoles", params = {"id"})
    public Map<String, Object> selectUserRoles(Integer id) {
        List<Map<String, Integer>> list = this.userRoleService.selectMaps(BeanUtils.instantiate(EntityWrapper.class)
                .setSqlSelect(BeanUtils.instantiate(Column.class).column("r_id").as("rId"))
                .where("u_id = {0}", id));
        if (CollectionUtils.isEmpty(list)) return ImmutableMap.of("status", "true", "data", Lists.newArrayList());

        List<Integer> rIds = list.stream().map(e -> e.get("rId")).collect(Collectors.toList());

        return ImmutableMap.of("status", "true", "data", rIds);
    }

    /**
     * 查询用户的部门
     * */
    @RequestMapping(value = "/selectUserOrg", params = {"id"})
    public Map<String, Object> selectUserOrg(Integer id) {
        List<Map<String, Integer>> list = this.userOrgService.selectMaps(BeanUtils.instantiate(EntityWrapper.class)
                .setSqlSelect(BeanUtils.instantiate(Column.class).column("o_id").as("oId"))
                .where("u_id = {0}", id));
        if (CollectionUtils.isEmpty(list)) return ImmutableMap.of("status", "true", "data", Lists.newArrayList());

        List<Integer> oIds = list.stream().map(e -> e.get("oId")).collect(Collectors.toList());

        return ImmutableMap.of("status", "true", "data", oIds);
    }

    /**
     * 查询用户拥有的菜单
     */
    @PostMapping(value = "/selectUserMenus",params = {"id"})
    public Map<String, Object> selectUserMenus(@RequestParam Map<String, Object> params, Integer id) {
        params.put("userId", id);
        params.put("Pid", 0);
        if(null == params.get("menuType")) params.put("menuType","menu");
        List<TSysMenuVo> menus = this.menuService.selectUserMenus(params);
        Iterator it = menus.iterator();
        while (it.hasNext()) {
            TSysMenuVo menu = (TSysMenuVo) it.next();
            params.put("Pid", menu.getId());
            menu.setChildren(this.menuService.selectUserMenus(params));
        }
        logger.info("查询用户菜单");
        return ImmutableMap.of("status", "true", "data", menus);

    }

    /**
     * 查询gjb的ID和name
     * */
    @GetMapping(value = "/selectUserByType")
    public Map<String, Object> selectUserByGJB(String type){
        type = StringUtils.isNotBlank(type)?type:"gjb";
        List<Map<String,Object>> users = this.service.selectMaps(new EntityWrapper<TSysUser>().setSqlSelect("id","name","staff_name as staffName").where("type={0}",type));
        return ImmutableMap.of("status", "true", "data", users);
    }


}
